package com.yk.neon.lib.util.log;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 */
public class IpAddressUtil {

	/**
	 * 获取本机IP地址
	 *
	 * @return
	 * @throws SocketException
	 */
	public static String getIpAddress() throws SocketException {
		Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
		while (allNetInterfaces.hasMoreElements()) {
			NetworkInterface netInterface = allNetInterfaces.nextElement();
			// 排除回送接口,非虚拟网卡,未在使用中的网口
			if (!netInterface.isLoopback() && !netInterface.isVirtual() && netInterface.isUp()) {
				Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					InetAddress ip = addresses.nextElement();
					if (ip instanceof Inet4Address) {
						return ip.getHostAddress();
					}
				}
			}
		}

		return null;
	}

}
